/**
 * AutoComplete Field - JavaScript Code
 *
 * This is a sample source code provided by fromvega.
 * Search for the complete article at http://www.fromvega.com
 *
 * @author fromvega
 *
 */

// global variables
var acListTotal   =  0;
var acListCurrent = -1;
var acDelay	 	  = 500;
var acURL	 	  = null;
var acSearchId	  = null;
var acTargetId	  = null;
var acTargetName  = null;
var acResultsId	  = null;
var acSearchField = null;
var acResultsDiv  = null;

function setAutoComplete(field_id, target_id, target_name, results_id, get_url){

	// initialize vars
	acSearchId  = "#" + field_id;
	acTargetId  = "#" + target_id;
	acTargetName  = "#" + target_name;
	acResultsId = "#" + results_id;
	acURL 		= get_url;
	
	// create the results div
//	$("div").append('<div class="returned_acc_list" id="' + results_id + '"></div>');
	$("div#resultID").append('<div id="' + results_id + '"></div>');
//	$("body").append('<div id="' + results_id + '"></div>');
	
	// register mostly used vars
	acSearchField	= $(acSearchId);
	acResultsDiv	= $(acResultsId);
	

	// reposition div25
	repositionResultsDiv();
	
	// on blur listener
	acSearchField.blur(function(){
		//clear the suggested list
		setTimeout("clearAutoComplete()", 200) 
		//bind "Add" button click to handle no-id place name
//		update_add_button_click();
	});
//	acSearchField.keydown(function (e) {
//		e.preventDefault(); //TODO: stop the form from being submitted when "Enter" pressed
//	});
	// on key up listener
	acSearchField.keyup(function (e) {
		// get keyCode (window.event is for IE)
		var keyCode = e.keyCode || window.event.keyCode;
		var lastVal = acSearchField.val();

		// check an treat up and down arrows
		if(updownArrow(keyCode)){
			return;
		}
		
		// check for an ENTER or ESC
		if(keyCode == 13 || keyCode == 27){
//			e.preventDefault(); //TODO: stop the form from being submitted when "Enter" pressed
			clearAutoComplete();
			return false;
		}

		// if is text, call with delay
		/*
		if (keyCode == 32)
			setTimeout(function () {autoComplete(lastVal)}, acDelay);
		
		*/
		//if (lastVal.length % 3 == 0)
			setTimeout(function () {autoComplete(lastVal)}, acDelay);
		
	});
	//bind the handler for "Add" button
	$(".belongButton").unbind('click').bind('click', update_belongto_id_list);
}

// treat the auto-complete action (delayed function)
function autoComplete(lastValue)
{
	
	// get the field value
	var part = acSearchField.val();
	
	// if it's empty clear the resuts box and return
	if(part == ''){
		clearAutoComplete();
		return;
	}

	// if it's equal the value from the time of the call, allow
	if(lastValue != part){
		return;
	}
	
	// get remote data as JSON
	$.getJSON(acURL + part, 
		{
			rtype: $("#rtype").val(),
		},
		function(json){
		console.log(json);
		// get the total of results
		var ansLength = acListTotal = json.length;

		// if there are results populate the results div
		if(ansLength > 0){

			var newData = '';
			
			// create a div for each result
			for(i=0; i < ansLength; i++) {
				newData += '<div class="unselected"  value="'+json[i].id+'" >' + json[i].name + '</div>';
			}

			// update the results div
			acResultsDiv.html(newData);
			acResultsDiv.css("display","block");
			
			// for all divs in results
			var divs = $(acResultsId + " > div");
			
			// on mouse over clean previous selected and set a new one
			divs.mouseover( function() {
				divs.each(function(){ this.className = "unselected"; });
				this.className = "selected";
			});

			// on click copy the result text to the search field and hide
			divs.click( function() {
				acSearchField.val($(this).text());
				//ANHNV : add the added id to the "#belong_to_id" span
				$("#newBelongToPlaceId").html($(this).attr('value'));
				//clear the search field
//				acSearchField.val('');
				clearAutoComplete();
			});

		} else {
			clearAutoComplete();
		}
	});
}

function update_remove_place_actions($newLi)
{
	//remove is clicked
	$newLi.addClass('belongToLi');
	$newLi.find("a").click(function(){
		//$newLi.remove();
		$(this).parent().parent().remove();
	});
}

var update_belongto_id_list = function ()
{
	//newPlaceId = $(selectedDiv).attr('value');
    newPlaceId = $("#newBelongToPlaceId").html();
	lengthPlace = $("#length").val();
	newPlaceName = acSearchField.val();
	var alreadyAdded = false;
	$ul = $(acTargetName +" ul");
	$ul.find("li").each(function(){
		if (($(this).attr('name') == newPlaceId) && ($(this).find("span:first").html() == newPlaceName))
		{
			alreadyAdded = true; return false;
		}
	});
	if (!alreadyAdded)
	{
		//add li
		$newLi = $("<li name='" + newPlaceId + "' ><span>" + newPlaceName + "</span><span>"+ ':' + "</span><span>" +
					lengthPlace +"</span>" + "km" + "<sup><a href='javascript:void()'>remove</a></sup></li>");
		
		$newLi.appendTo($(acTargetName +" ul"));
		
		//update dom
		update_remove_place_actions($newLi);

		//reset the fields
		$("#newBelongToPlaceId").html('');
		acSearchField.val('');
		$("#length").val('');
	}
	else
	{
		alert('This place has already been added');
	}
}

// clear auto complete box
function clearAutoComplete()
{
	acResultsDiv.html('');
	acResultsDiv.css("display","none");
}

// reposition the results div accordingly to the search field
function repositionResultsDiv()
{
	// get the field position
	var sf_pos    = acSearchField.offset();
	var sf_top    = sf_pos.top;
	var sf_left   = sf_pos.left;

	// get the field size
	var sf_height = acSearchField.height();
	var sf_width  = acSearchField.width();

	// apply the css styles - optimized for Firefox
//	acResultsDiv.css("position","absolute");
//	acResultsDiv.css("left", sf_left - 2);
//	acResultsDiv.css("top", sf_top + sf_height + 5);
//	acResultsDiv.css("width", sf_width - 2);
	
	//ANH: config position display....
	acResultsDiv.css("position","absolute");
	acResultsDiv.css("left", sf_left + 150);
	acResultsDiv.css("top", sf_top + sf_height + 100);
	acResultsDiv.css("width", sf_width - 15);
	/*acResultsDiv.css("z-index", 1);*/
	
}


// treat up and down key strokes defining the next selected element
function updownArrow(keyCode) {
	if(keyCode == 40 || keyCode == 38){

		if(keyCode == 38){ // keyUp
			if(acListCurrent == 0 || acListCurrent == -1){
				acListCurrent = acListTotal-1;
			}else{
				acListCurrent--;
			}
		} else { // keyDown
			if(acListCurrent == acListTotal-1){
				acListCurrent = 0;
			}else {
				acListCurrent++;
			}
		}

		// loop through each result div applying the correct style
		acResultsDiv.children().each(function(i){
			if(i == acListCurrent){
				acSearchField.val($(this).text()/*.childNodes[0].nodeValue*/);
				this.className = "selected";
			} else {
				this.className = "unselected";
			}
		});

		return true;
	} else {
		// reset
		acListCurrent = -1;
		return false;
	}
}



